package com.gmall.user.server.restapi;

import com.alibaba.fastjson.JSONObject;
import com.gmall.common.model.Response;
import com.gmall.common.model.ResultList;
import com.gmall.user.api.form.UserQueryForm;
import com.gmall.user.api.po.User;
import com.gmall.user.server.biz.UserBiz;
import com.gmall.user.server.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author HL.Wu
 * @date 2020/5/28 13:10
 * Copyright ©https://blog.csdn.net/qq_31150503 Copyright@2009-2020 AII Right Reserve
 */
@RestController
@Slf4j
@RequestMapping("/user")
public class UserApi {

    @Autowired
    private UserService userService;
    @Autowired
    private UserBiz userBiz;

    @GetMapping("findUserById")
    public User findUserById(@RequestParam("id") String id){
        return userService.findById(id);
    }

    @PostMapping("/list")
    public ResultList<User> list(@RequestBody UserQueryForm userQueryForm) throws Exception {
        ResultList<User> resultList = ResultList.emptyList();
        // 查询用户集合数据
        int cnt = userService.count(userQueryForm);
        List<User> list = userService.list(userQueryForm);
        resultList.setResult(list);
        resultList.setPageNum(userQueryForm.getPageNum());
        resultList.setPageSize(userQueryForm.getPageSize());
        resultList.setTotal(cnt);
        return resultList;
    }

    @GetMapping("/findUserByName")
    public User findUserByName(@RequestParam("userName") String userName, HttpServletRequest request){
        String token = request.getHeader("sign");
        log.info("current sign info is {}",token);
        UserQueryForm userQueryForm = new UserQueryForm();
        userQueryForm.setUsername(userName);
        return userService.findByForm(userQueryForm);
    }

    @GetMapping("/getAccountInfo")
    public Response<JSONObject> getAccountInfo(@RequestParam("userId") String userId){
        return userBiz.getAccountInfo(userId);
    }

    @PostMapping("/save")
    public int save(@RequestBody JSONObject jsonObject){
       return userBiz.saveUserInfo(jsonObject);
    }

    @PostMapping("/update")
    public int update(@RequestBody User user){
        return userService.update(user);
    }

    @GetMapping("/delete")
    public int delete(@RequestParam("id") String id){
        return userService.deleteById(id);
    }

}
